package com.mycat.task.proxy;

import com.mycat.task.entity.ScheduleTask;
import com.mycat.task.service.ScheduleTaskExecuteDetailService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 定时任务代理类
 *
 * @author roger.
 * @email 190642964@qq.com
 * @create 2017-03-27
 */
public class ScheduleJobProxy implements Job {

    private static final Logger logger = LoggerFactory.getLogger(ScheduleJobProxy.class);

    public static final String DATA_TARGET_KEY = "target";
    public static final String DATA_TRIGGER_KEY = "trigger";
    public static final String DATA_TRIGGER_PARAM_KEY = "trigger_param";
    public static final String DATA_TASK_KEY = "task";

    @Autowired
    private ScheduleTaskExecuteDetailService scheduleTaskExecuteDetailService;

    @Override
    public void execute(JobExecutionContext ctx) throws JobExecutionException {

        JobDetail jobDetail = ctx.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        Object target = jobDataMap.get(DATA_TARGET_KEY);
        Method method = (Method) jobDataMap.get(DATA_TRIGGER_KEY);
        ScheduleTask scheduleTask = (ScheduleTask) jobDataMap.get(DATA_TASK_KEY);
        Object[] param = (Object[]) jobDataMap.get(DATA_TRIGGER_PARAM_KEY);

        try {
            logger.debug("这是定时任务的代理................开始执行,{}" + scheduleTaskExecuteDetailService);
            method.invoke(target, param);
            logger.debug("这是定时任务的代理................执行完毕");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
